<?php

namespace app\common\model;

use app\api\model\DeveloperException;
use app\api\model\ServerException;
use app\api\model\TokenException;
use app\api\model\UserException;
use think\facade\Cache;
use think\facade\Db;

class Region extends Base
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    /**
     * 前端定位取城市
     * @param $longitude
     * @param $latitude
     * @return array
     * @throws UserException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    static public function locationCity($longitude,$latitude){
        if(empty($longitude)||empty($latitude)){
            $location = self::ipToCity();
        }else{
            $location = self::coordinatesToCity($longitude,$latitude);
        }

        //开通状态
        $status = self::where('id',$location['city_id'])->value('status');

        if($status){
            return [
                'location_city'=>$location['city'],
                'location_city_id'=>$location['city_id'],
                'location_status'=>$status,
                'change_city'=>$location['city'],
                'change_city_id'=>$location['city_id']
            ];

        }else{
            //最近一个开通的城市
            $city_list = self::getCityCache();
            $min_distance = 0;
            $city = [];
            foreach ($city_list['city'] as $key=>$item){
                if($key==0){
                    $city = $item;
                    $min_distance = distance($latitude,$longitude,$item['latitude'],$item['longitude']);
                }else{
                    $distance = distance($latitude,$longitude,$item['latitude'],$item['longitude']);
                    if($distance<$min_distance){
                        $min_distance = $distance;
                        $city = $item;
                    }
                }
            }

            return [
                'location_city'=>$location['city'],
                'location_city_id'=>$location['city_id'],
                'location_status'=>$status,
                'change_city'=>$city['name'],
                'change_city_id'=>$city['id']
            ];
        }
    }

    /**
     * 高德地图周边配套
     * @param $longitude
     * @param $latitude
     * @return array[]
     * @throws UserException
     * @throws \Throwable
     */
    static public function getMapFacility($longitude,$latitude){
        //教育查幼儿园
        $school = self::aroundFacility($longitude,$latitude,'141204');
        $school_list = [];
        foreach ($school as $key=>$item){
            if($key>=3){
                break;
            }
            $school_list[] = [
                'title'=>$item['name'],
                'distance'=>'直线'.show_km($item['distance'])
            ];
        }

        //交通查公交
        $bus = self::aroundFacility($longitude,$latitude,'150700');
        $bus_list = [];
        foreach ($bus as $key=>$item){
            if($key>=3){
                break;
            }
            $title = str_replace('(公交站)',"({$item['address']})",$item['name']);
            $bus_list[] = [
                'title'=>$title,
                'distance'=>'直线'.show_km($item['distance'])
            ];
        }

        //医疗查医疗保健
        $hospital = self::aroundFacility($longitude,$latitude,'090100|090101|090102');
        $hospital_list = [];
        foreach ($hospital as $key=>$item){
            if($key>=3){
                break;
            }
            $hospital_list[] = [
                'title'=>$item['name'],
                'distance'=>'直线'.show_km($item['distance'])
            ];
        }

        //生活购物
        $life = self::aroundFacility($longitude,$latitude,'060000');
        $life_list = [];
        foreach ($life as $key=>$item){
            if($key>=3){
                break;
            }
            $life_list[] = [
                'title'=>$item['name'],
                'distance'=>'直线'.show_km($item['distance'])
            ];
        }

        //休闲
        $play = self::aroundFacility($longitude,$latitude,'080000');
        $play_list = [];
        foreach ($play as $key=>$item){
            if($key>=3){
                break;
            }
            $play_list[] = [
                'title'=>$item['name'],
                'distance'=>'直线'.show_km($item['distance'])
            ];
        }

        return [
            [
                'title'=>'教育',
                'data'=>$school_list
            ],
            [
                'title'=>'交通',
                'data'=>$bus_list
            ],
            [
                'title'=>'医疗',
                'data'=>$hospital_list
            ],
            [
                'title'=>'生活',
                'data'=>$life_list
            ],
            [
                'title'=>'休闲',
                'data'=>$play_list
            ],
        ];
    }

    /**
     * 周边配套
     * @param $longitude
     * @param $latitude
     * @return array[]
     * @throws UserException
     * @throws \Throwable
     */
    static public function getTxMapFacility($city_id,$longitude,$latitude){
        //教育查幼儿园
        $school = self::txKeywordSearch($city_id,$longitude,$latitude,'幼儿园');
        $school_list = [];
        foreach ($school as $key=>$item){
            if($key>=3){
                break;
            }
            $school_list[] = [
                'title'=>$item['title'],
                'distance'=>'直线'.show_km($item['_distance']),
                'location'=>$item['location']['lng'].','.$item['location']['lat']
            ];
        }

        //交通查公交
        $bus = self::txKeywordSearch($city_id,$longitude,$latitude,'公交站');
        $bus_list = [];
        foreach ($bus as $key=>$item){
            if($key>=3){
                break;
            }
            $title = str_replace('[公交站]',"({$item['address']})",$item['title']);
            $bus_list[] = [
                'title'=>$title,
                'distance'=>'直线'.show_km($item['_distance']),
                'location'=>round($item['location']['lng'],6).','.round($item['location']['lat'],6)
            ];
        }

        //医疗查医疗保健
        $hospital = self::txKeywordSearch($city_id,$longitude,$latitude,'医疗保健');
        $hospital_list = [];
        foreach ($hospital as $key=>$item){
            if($key>=3){
                break;
            }
            $hospital_list[] = [
                'title'=>$item['title'],
                'distance'=>'直线'.show_km($item['_distance']),
                'location'=>$item['location']['lng'].','.$item['location']['lat']
            ];
        }

        //生活购物
        $life = self::txKeywordSearch($city_id,$longitude,$latitude,'便利');
        $life2 = self::txKeywordSearch($city_id,$longitude,$latitude,'超市');
        $life3 = self::txKeywordSearch($city_id,$longitude,$latitude,'购物');

        $life = array_merge($life,$life2,$life3);
        $life = uniqueArr($life,'title');
        $distance = array_column($life,'_distance');
        array_multisort($distance,SORT_ASC,$life);

        $life_list = [];
        foreach ($life as $key=>$item){
            if($key>=3){
                break;
            }
            $life_list[] = [
                'title'=>$item['title'],
                'distance'=>'直线'.show_km($item['_distance']),
                'location'=>$item['location']['lng'].','.$item['location']['lat']
            ];
        }

        //休闲
        $play = self::txKeywordSearch($city_id,$longitude,$latitude,'娱乐');
        $play2 = self::txKeywordSearch($city_id,$longitude,$latitude,'体育');
        $play3 = self::txKeywordSearch($city_id,$longitude,$latitude,'公园');
        $play = array_merge($play,$play2,$play3);
        $play = uniqueArr($play,'title');
        $distance = array_column($play,'_distance');
        array_multisort($distance,SORT_ASC,$play);
        $play_list = [];
        foreach ($play as $key=>$item){
            if($key>=3){
                break;
            }
            $play_list[] = [
                'title'=>$item['title'],
                'distance'=>'直线'.show_km($item['_distance']),
                'location'=>$item['location']['lng'].','.$item['location']['lat']
            ];
        }

        return [
            [
                'title'=>'教育',
                'data'=>$school_list
            ],
            [
                'title'=>'交通',
                'data'=>$bus_list
            ],
            [
                'title'=>'医疗',
                'data'=>$hospital_list
            ],
            [
                'title'=>'生活',
                'data'=>$life_list
            ],
            [
                'title'=>'休闲',
                'data'=>$play_list
            ],
        ];
    }

    /**
     * 经纬度解析城市
     * @param $longitude
     * @param $latitude
     * @return array|mixed
     * @throws UserException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    static public function coordinatesToCity($longitude,$latitude){

        if(empty($longitude)||empty($latitude)){
            throw new UserException('经度纬度不可为空');
        }

        $expire = '259200';//三天
        $cache_name = 'zfn_region_coordinates_new_'.$longitude.'_'.$latitude;

        $data = Cache::store('redis')->remember($cache_name, function () use($latitude,$longitude){
            //使用高德的逆地图解析
            $gmap_key = Settings::getSystem('gmap_skey');

            $url = 'https://restapi.amap.com/v3/geocode/regeo?output=json&location='.$longitude.','.$latitude.'&key='.$gmap_key;

            $res = file_get_contents($url);
            if(empty($res)){
                throw new UserException('经纬度解析失败');
            }
            $res = json_decode($res,true);

            if($res['status']!=1){
                throw new UserException($res['info']);
            }

            $province = $res['regeocode']['addressComponent']['province'];
            if(in_array($province,['北京市','天津市','上海市','重庆市'])){
                $city = $province;
            }elseif (in_array($province,['香港特别行政区','澳门特别行政区','台湾省'])){
                $province = str_replace('特别行政区','',$province);
                $province = str_replace('省','',$province);
                $city = $province;
            }else{
                $city = $res['regeocode']['addressComponent']['city'];
            }

            //查城市
            if(empty($city)){
                throw new UserException($longitude.','.$latitude.'，经纬度解析失败');
            }
            $where = [
                ['name','like',$city.'%'],
                ['level','=',2]
            ];
            $city_info = self::where($where)->field('id,name,parent_id')->findOrEmpty()->toArray();
            if(!$city_info){
                throw new UserException('城市解析失败');
            }

            //查区县
            $area = '';
            if($city == '台湾'){
                $area = '台湾';
            }elseif(!empty($res['regeocode']['addressComponent']['district'])){
                $area = $res['regeocode']['addressComponent']['district'];
            }else{
                if(!empty($res['regeocode']['addressComponent']['township'])){
                    $area = $res['regeocode']['addressComponent']['township'];
                }
            }

            if(empty($area)){
                throw new UserException('区县解析失败');
            }

            $where = [
                ['parent_id','=',$city_info['id']],
                ['name','like',$area.'%'],
                ['level','=',3]
            ];
            $area_info = Db::name('region')->where($where)->field('id,name')->find();
            if(!$area_info){
                throw new UserException('区县解析失败');
            }

            //乡镇街道
            $town = '';
            $town_id = 0;

            if(isset($res['regeocode']['addressComponent']['township']) && !empty($res['regeocode']['addressComponent']['township'])){
                $town = $res['regeocode']['addressComponent']['township'];;
                if($town!=$area){
                    $where = [
                        ['parent_id','=',$area_info['id']],
                        ['name','like',$town.'%'],
                        ['level','=',4]
                    ];
                    $town_id = Db::name('region')->where($where)->value('id');
                    $town_id = intval($town_id);
                }
            }

            //省市区单独保存了详细地址不显示省市区
            $place = $res['regeocode']['formatted_address'];
            $place = str_replace($res['regeocode']['addressComponent']['province'],'',$place);
            $place = str_replace($city,'',$place);
            $place = str_replace($area,'',$place);

            $data = [
                'province'=>$province,
                'province_id'=>$city_info['parent_id'],
                'city'=>$city,
                'city_id'=>$city_info['id'],
                'area'=>$area,
                'area_id'=>$area_info['id'],
                'town'=>$town,
                'town_id'=>$town_id,
                'adcode'=>$res['regeocode']['addressComponent']['adcode'],
                'place'=>$place,
            ];

            return $data;
        }, $expire);
        return $data;
    }

    /**
     * ip定位城市
     * @return mixed
     * @throws \Throwable
     */
    static public function ipToCity(){
        $ip = request()->ip();
        if(empty($ip)){
            throw new UserException('ip为空');
        }
        if (strpos($ip, '192.168.') !== false) {
            $ip = '123.132.250.106';
        }

        $expire = '259200';//三天
        $cache_name = 'zfn_region_ip_new_v1_'.$ip;

        $data = Cache::store('redis')->remember($cache_name, function () use($ip){
            //使用高德的逆地图解析
            $gmap_key = Settings::getSystem('gmap_skey');

            $url = 'https://restapi.amap.com/v3/ip?ip='.$ip.'&output=json&key='.$gmap_key;

            $res = file_get_contents($url);

            if(empty($res)){
                throw new UserException('ip解析失败');
            }

            $res = json_decode($res,true);

            if($res['status']!=1){
                throw new UserException($res['info']);
            }

            if($res['province']=='局域网'){
                throw new UserException('局域网ip无法定位');
            }

            $province = $res['province'];

            if (in_array($province,['香港特别行政区','澳门特别行政区','台湾省'])){
                $province = str_replace('特别行政区','',$province);
                $province = str_replace('省','',$province);
                $city = $province;
            }else{
                $city = $res['city'];
            }

            //查城市
            if(empty($city)){
//                throw new UserException($ip.'解析失败');
                $city_info = self::where('id','1205')->field('id,name,parent_id,center')->findOrEmpty()->toArray();
                if(!$city_info){
                    throw new UserException('城市解析失败');
                }
                $city = '临沂市';
                $province = '山东省';
            }else{
                $where = [
                    ['name','like',$city.'%'],
                    ['level','=',2]
                ];
                $city_info = self::where($where)->field('id,name,parent_id,center')->findOrEmpty()->toArray();
                if(!$city_info){
                    throw new UserException('城市解析失败');
                }
            }


            //城市中心经纬度
            $lnglat = explode(',',$city_info['center']);

            $data = [
                'province'=>$province,
                'province_id'=>$city_info['parent_id'],
                'city'=>$city,
                'city_id'=>$city_info['id'],
                'adcode'=>$res['adcode'],
                'longitude'=>$lnglat[0],
                'latitude'=>$lnglat[1],
            ];

            return $data;
        }, $expire);
        return $data;

    }

    /**
     * 高德地图行政区域查询
     * @param $keywords
     * @return mixed
     * @throws DeveloperException
     * @throws \Throwable
     */
    static public function adcodePoline($keywords){
        $keywords = reInject($keywords);
        if($keywords==''){
            throw new DeveloperException('keywords不可为空');
        }

        $expire = '864000';//10天
        $cache_name = 'zfn_region_config_district_new_v1.1_'.md5($keywords);

        $data = Cache::store('redis')->remember($cache_name, function () use($keywords){
            //使用高德
            $gmap_key = Settings::getSystem('gmap_skey');

            $url = "https://restapi.amap.com/v3/config/district?key={$gmap_key}&keywords={$keywords}&subdistrict=0&extensions=all";

            $res = file_get_contents($url);

            if(empty($res)){
                throw new UserException('高德查询失败');
            }

            $res = json_decode($res,true);

            if($res['status']!=1){
                throw new UserException($res['info']);
            }

            return $res;
        }, $expire);
        return $data;

    }

    /**
     * 根据行政编码获取天气信息
     * @param $adcode string 地区行政编码
     * @return array|mixed
     * @throws \Throwable
     */
    static public function locationWeather($longitude,$latitude){
        $data = [
            'code'=>0,
            'info'=>'',
            'temperature'=>'',
            'date'=>date('m/d/Y'),
            'weather'=>'',
        ];

        try{

            //获取经纬度对应行政编号
            $region = self::coordinatesToCity($longitude,$latitude);
            $adcode = $region['adcode'];

            $expire = '600';//十分钟一更新
            $cache_name = 'zfn_region_weatherinfo_'.$adcode;

            $data = Cache::store('redis')->remember($cache_name, function () use($adcode,$data){
                //使用高德地图天气接口
                $gmap_skey = Settings::getSystem('gmap_skey');

                $url = 'https://restapi.amap.com/v3/weather/weatherInfo?city='.$adcode.'&key='.$gmap_skey.'&extensions=base';

                $res = file_get_contents($url);

                if(empty($res)){
                    $data['info'] = '天气获取失败';
                    return $data;
                }

                $res = json_decode($res,true);

                if($res['status']!=1){
                    $data['info'] = $res['info'];
                    return $data;
                }

                //实时天气详情
                $detail = $res['lives'][0];

                if(isset($detail['temperature'])){
                    $data['code'] = 1;
                    $data['info'] = 'ok';
                    $data['temperature'] = $detail['temperature'];

                    //气象
                    if(isset($detail['weather'])){
                        $data['weather'] = $detail['weather'];
                    }

                    if(isset($detail['winddirection'])&&isset($detail['windpower'])){
                        $data['weather'] .= '，'.$detail['winddirection'].'风'.$detail['windpower'].'级';
                    }

                    trim($data['weather'],'，');

                }else{
                    $data['info'] = '行政编码有误或无具体天气信息';
                    return $data;
                }

                return $data;
            }, $expire);
        }catch (\Exception $exception){
            $data['info'] = $exception->getMessage();
        }


        return $data;
    }

    /**
     * 高德poi搜索 周边搜索 配额很低 企业认证 单日1000
     * @param $longitude
     * @param $latitude
     * @param string $types 幼儿园 141204 小学 141203 中学 141202 公交相关 150700 医疗保健服务090000
     * @return mixed
     * @throws UserException
     * @throws \Throwable
     */
    static public function aroundFacility($longitude,$latitude,$types){

        if(empty($longitude)||empty($latitude)){
            throw new UserException('经度纬度不可为空');
        }

        $expire = '864000';//10天
        $cache_name = 'zfn_region_around_facility_'.$longitude.'_'.$latitude.'_types_'.$types;

        $data = Cache::store('redis')->remember($cache_name, function () use($latitude,$longitude,$types){
            //使用高德的逆地图解析
            $gmap_key = Settings::getSystem('gmap_skey');

            $url = "https://restapi.amap.com/v3/place/around?key={$gmap_key}&location={$longitude},{$latitude}&radius=5000&types={$types}&sortrule=distance";

            $res = file_get_contents($url);
            if(empty($res)){
                throw new UserException('经纬度解析失败');
            }
            $res = json_decode($res,true);

            if($res['status']!=1){
                throw new UserException($res['info']);
            }
            return $res['pois'];
        }, $expire);
        return $data;
    }

    /**
     * 腾讯关键词输入提示 经纬度不为空时会返回距离
     * @param $city
     * @param $lng
     * @param $lat
     * @param $keyword
     * @return mixed
     * @throws UserException
     * @throws \Throwable
     */
    static public function txKeywordSearch($city,$lng,$lat,$keyword){
        if(is_numeric($city)){
            $city = Region::getRegionName(intval($city));
            if(!$city){
                throw new UserException('城市id有误');
            }
        }

        $keyword = reInject($keyword);
        if($keyword===''){
            throw new UserException('关键词不可为空');
        }

        $expire = '864000';//10天
        $cache_name = "zfn_region_tx_keyword_search_{$city}_{$lng}_{$lat}_{$keyword}_v1";

        $data = Cache::store('redis')->remember($cache_name, function () use($city,$lng,$lat,$keyword){
            //使用高德的逆地图解析
            $tmap_key = Settings::getSystem('tmap_key');

            $url = "https://apis.map.qq.com/ws/place/v1/suggestion/?region={$city}";

            if($lng&&$lat){
                $url .= "&location={$lat},{$lng}";
            }

            $url .= "&policy=1&keyword={$keyword}&address_format=short&key={$tmap_key}&page_index=1&page_size=10";

            $res = file_get_contents($url);
            if(empty($res)){
                throw new UserException('经纬度解析失败');
            }
            $res = json_decode($res,true);

            if($res['status']!=0){
                throw new UserException($res['message']);
            }
            return $res['data'];
        }, $expire);
        return $data;
    }


    /*******操作数据库region表的方法********/
    /**
     * 缓存名
     * @return string
     */
    static public function cityCacheName(){
        return 'zfn_city_list';
    }

    /**
     * 保存城市
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function saveCityCache(){
//        $hot = self::where('is_hot','=',1)
//            ->where('status','=',1)
//            ->where('level','=',2)
//            ->order('sort DESC,id DESC')
//            ->field('id,name,center')
//            ->select()
//            ->toArray();
//
//        foreach ($hot as &$item){
//            $res = explode(',',$item['center']);
//            $item['longitude'] = $res['0'];
//            $item['latitude'] = $res['1'];
//            unset($item['center']);
//        }
//        unset($item);

        $list = self::where('status','=',1)
            ->where('level','=',2)
            ->field('id,name,short_name,center')
            ->order('short_name ASC,sort DESC')
            ->select()
            ->toArray();

        foreach ($list as &$item){
            $res = explode(',',$item['center']);
            $item['longitude'] = $res['0'];
            $item['latitude'] = $res['1'];
            unset($item['center']);
        }
        unset($item);

        $data = [
//            'hot'=>$hot,
            'city'=>$list
        ];
        Cache::store('redis')->set(self::cityCacheName(),$data);
        return $data;
    }

    /**
     * 获取城市
     * @return array|mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    static public function getCityCache(){
        $name = self::cityCacheName();
        $redis = Cache::store('redis');
        $data = $redis->get($name);
        if(!$data){
            $data = self::saveCityCache();
        }
        return $data;
    }

    /**
     * 获取城市下区县
     * @return array|mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    static public function getCityArea($city_id,$with_center=false){
        $expire = '864000';//10天
        $cache_name = 'zfn_region_area_v1.3_'.$city_id;
        $data = Cache::store('redis')->remember($cache_name,function () use ($city_id){
            $list = self::where('parent_id','=',$city_id)
                ->where('level','=',3)
                ->field('id,name as title,center,adcode')
                ->order('sort DESC')
                ->select()
                ->toArray();

            return $list;
        },$expire);

        foreach ($data as &$item){
            if($with_center){
                $arr = explode(',',$item['center']);
                $item['longitude'] = $arr[0];
                $item['latitude'] = $arr[1];
            }
            unset($item['center']);
        }
        unset($item);

        return $data;
    }

    /**
     * 获取某城市下区县和商圈
     * @param $city_id
     * @return array|mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function getCityAreaDistrict($city_id,$with_center=false){
        $area = self::getCityArea($city_id,$with_center);

        //区县添加不限
        $area_first = ['id'=>0,'title'=>'不限','adcode'=>''];
        if($with_center){
            $area_first = [
                'id'=>0,
                'title'=>'不限',
                'longitude'=>'',
                'latitude'=>'',
                'adcode'=>''
            ];
        }

        //商圈添加不限
        $dis_first = ['id'=>0,'title'=>'不限'];
        if($with_center){
            $dis_first = [
                'id'=>0,
                'title'=>'不限',
                'longitude'=>'',
                'latitude'=>'',
                'path'=>[]
            ];
        }

        array_unshift($area,$area_first);

        foreach ($area as &$item){
            if($item['id']>0){
                $district = District::getList(0,$item['id']);
                $item['district'] = [
                    $dis_first
                ];

                foreach ($district as $dis){
                    if($with_center){
                        $item['district'][] = [
                            'id'=>$dis['id'],
                            'title'=>$dis['title'],
                            'longitude'=>$dis['longitude'],
                            'latitude'=>$dis['latitude'],
                            'path'=>empty($dis['path']) ? [] : json_decode($dis['path'],true),
                        ];
                    }else{
                        $item['district'][] = [
                            'id'=>$dis['id'],
                            'title'=>$dis['title']
                        ];
                    }
                }
            }else{
                $item['district'] = [];
            }

        }
        unset($item);

        return $area;
    }

    /**
     * 获取地区名称
     * @param $id
     * @return mixed|string
     */
    static public function getRegionName($id){
        if(!$id){
            return '';
        }
        $name = Db::name('region')
            ->where('id','=',$id)
            ->cache(true,'359200')
            ->value('name');
        return $name;
    }

    /**
     * 获取地区信息
     * @param $id
     * @return array|mixed|string|Db|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function getRegionInfo($id){
        if(!$id){
            return '';
        }
        $info = Db::name('region')
            ->where('id','=',$id)
            ->cache(true,'359200')
            ->find();
        return $info;
    }

    /**
     * 获取地区名称
     * @param $id
     * @return mixed|string
     */
    static public function getRegionNamePath($pro_id='',$city_id='',$area_id='',$town_id=''){
        $name_path = '';
        $cache_time = 359200;
        if($town_id){
            $name_path = Db::name('region')
                ->where('id','=',$town_id)
                ->cache(true,$cache_time)
                ->value('name_path');
        }elseif($area_id){
            $name_path = Db::name('region')
                ->where('id','=',$area_id)
                ->cache(true,$cache_time)
                ->value('name_path');
        }elseif($city_id){
            $name_path = Db::name('region')
                ->where('id','=',$city_id)
                ->cache(true,$cache_time)
                ->value('name_path');
        }elseif($pro_id){
            $name_path = Db::name('region')
                ->where('id','=',$pro_id)
                ->cache(true,$cache_time)
                ->value('name_path');
        }

        return $name_path;
    }


    /**
     * android 用到的地区json
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function androidJson(){
        $cache_name = 'zfn_android_region_json_v1.1';

        $data = Cache::store('redis')->remember($cache_name,function (){
            $list = Db::name('region')
                ->where('level',1)
                ->field('id,name')
                ->order('sort DESC')
                ->select()
                ->toArray();
            foreach ($list as &$item){
                $city = Db::name('region')
                    ->where('parent_id','=',$item['id'])
                    ->where('level','=',2)
                    ->field('id,name')
                    ->order('sort DESC')
                    ->select()
                    ->toArray();
                foreach ($city as &$c){
                    $area = Db::name('region')
                        ->where('parent_id','=',$c['id'])
                        ->where('level','=',3)
                        ->field('id,name')
                        ->order('sort DESC')
                        ->select()
                        ->toArray();
                    $c['area'] = $area;
                }
                $item['city'] = $city;
            }
            return $list;
        },'864000');

        return $data;
    }

    /**
     * ios 用到的地区json
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function iosJson(){
        $cache_name = 'zfn_ios_region_json_v1.1';
        $data = Cache::store('redis')->remember($cache_name,function (){
            $list = Db::name('region')
                ->where('level',1)
                ->field('id,name')
                ->order('sort DESC')
                ->select()
                ->toArray();
            foreach ($list as &$item){
                $city = Db::name('region')
                    ->where('parent_id','=',$item['id'])
                    ->where('level','=',2)
                    ->field('id,name')
                    ->order('sort DESC')
                    ->select()
                    ->toArray();
                foreach ($city as &$c){
                    $area = Db::name('region')
                        ->where('parent_id','=',$c['id'])
                        ->where('level','=',3)
                        ->field('id,name')
                        ->order('sort DESC')
                        ->select()
                        ->toArray();
                    $c['childs'] = $area;
                }
                $item['childs'] = $city;
            }
            return $list;
        },864000);
        return $data;
    }

}